"""
链接MySQL服务器，执行查询操作
"""

import MySQLdb

# no = int(input('编号：'))
# name = input('名称：')
# loc = input('所在地：')
from sql_week1.partial__01 import create_connect


class Course:
    def __init__(self, id=None, name=None, credit=None):
        self.id = id
        self.name = name
        self.credit = credit

    def __str__(self):
        return f'编号:{self.id}\n名称:{self.name}\n学分:{self.credit}'

# 第一步：创建连接对象


conn = create_connect(database='school')
# host主机地址
try:
    # 第二部：通过链接对象获取游标对象
    with conn.cursor(MySQLdb.cursors.DictCursor) as cursor:
        # 第三步:通过游标对象向数据库服务器发出SQL语句
        cursor.execute('select cou_id as id, cou_name as name, cou_credit as credit from tb_course')
        # 第四步:获取查询结果(通过游标抓取数据)
        # fetchone() ----> 抓取一条数据 -----> 元组
        # fetchall() ----> 抓取所有数据 -----> 嵌套元组
        # fetchmany() ----> 抓取指定数量的数据 ---> 嵌套元组
        row_dict = cursor.fetchone()

        while row_dict:
            course = Course(**row_dict)
            # 就是把字典里的键值对变成参数名和参数值
            print(course.name, course.credit)
            print('-' * 20)
            row = cursor.fetchone()

except MySQLdb.MySQLError as err:
    print(err)

finally:
    # 第五步：关闭连接
    # 数据库可以链接的游标数是有限的用完了之后要及时释放连接
    conn.close()
